package com.atguigu.gulimall.gateway.config;

import com.alibaba.csp.sentinel.adapter.gateway.sc.callback.BlockRequestHandler;
import com.alibaba.csp.sentinel.adapter.gateway.sc.callback.GatewayCallbackManager;
import com.alibaba.fastjson.JSON;
import com.atguigu.common.exception.BizCodeEnume;
import com.atguigu.common.utils.R;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.reactive.function.server.ServerResponse;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/**
 * @title: SentinelGatewayConfig
 * @Author syh
 * @Date: 2022/7/20 10:28
 * @Version 1.0
 */

@Configuration
public class SentinelGatewayConfig {

    public SentinelGatewayConfig(){
        // 设置阻塞处理器
        GatewayCallbackManager.setBlockHandler(new BlockRequestHandler(){
            // 网关限流了请求,就会调用这个回调    Mono  Flu:Spring5的响应式编程
            @Override
            public Mono<ServerResponse> handleRequest(ServerWebExchange exchange, Throwable t) {
                R error = R.error(BizCodeEnume.TOO_MANY_REQUEST.getCode(), BizCodeEnume.TOO_MANY_REQUEST.getMsg());
                String jsonString = JSON.toJSONString(error);

                Mono<ServerResponse> mono = ServerResponse.ok().body(Mono.just(jsonString), String.class);
                return mono;
            }
        });
    }

}
